package com.note.controller;

import cn.hutool.crypto.SecureUtil;
import com.note.pojo.User;
import com.note.service.UserService;
import com.note.utils.CodeUtils;
import com.note.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //跳转到登录页面
    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }
    //跳转到注册页面
    @RequestMapping("/toreg")
    public String toreg(){
        return "register";
    }

    @ResponseBody   //不传视图
    @RequestMapping("/login")
    public String login(String loginname, String password, HttpSession session){
        
        String password1 = SecureUtil.md5(password);
        String flag = userService.login(loginname, password1,session);
        System.out.println("测试"+flag);
        return flag;
    }

    //注册验证用户名是否可用
    @ResponseBody
    @RequestMapping("/checkname")
    public String checkname(String loginname){
        String checkcode = userService.findNameByName(loginname);
        return checkcode;
    }

    //邮箱验证码
    @ResponseBody
    @RequestMapping("/emailcod")
    public String emailcod(String email){

        String code1 = CodeUtils.generateNumber(6);
        MailUtils.send(email,code1);
        String code = SecureUtil.md5(code1);
        return code;
    }

    //文件上传
    @ResponseBody
    @RequestMapping("/upload")
    public Map upload(MultipartFile file,HttpServletRequest request){

        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String fileName = file.getOriginalFilename();
                Date date = new Date();
                String uuid = UUID.randomUUID()+"";
                String filepath = request.getServletContext().getRealPath("/upload/"+uuid+"/"+fileName);
                File files=new File(filepath);

                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
                Map<String,Object> map2=new HashMap<>();
                Map<String,Object> map=new HashMap<>();
                map.put("code",0);
                map.put("msg","");
                map.put("data",map2);
                map2.put("src","upload/"+uuid+"/"+fileName);
                return map;
            }

        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("msg","");
        return map;

    }


    //注册请求
    @ResponseBody
    @RequestMapping("/register")
    public String register(String loginname,String password,String email,String nickname,String avatar,String vcode,String ecode){
        User user = new User();
        user.setLoginname(loginname);
        user.setEmail(email);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setCreatetime(new Date());
        user.setPassword(SecureUtil.md5(password));
//        System.out.println("用户"+user);
//        System.out.println(SecureUtil.md5(vcode));
//        System.out.println(ecode);
//        System.out.println(ecode.equals(SecureUtil.md5(vcode)));
        if (ecode.equals(SecureUtil.md5(vcode))){
            System.out.println("成功");
            userService.register(user);
            return "success";
        }else{
            return "no";
        }
    }

    //安全退出
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/user/tologin";
    }

    //跳转到个人信息页面
    @RequestMapping("/personinfo")
    public String personinfo(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        model.addAttribute("user",user);
        return "personinfo";
    }


    //跳转到修改密码页面
    @RequestMapping("/editpwd")
    public String editpwd(HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        model.addAttribute("user",user);
        return "editpwd";
    }

    //修改密码提交 （通过原密码和邮箱验证修改密码）
    @ResponseBody
    @RequestMapping("/newpwd")
    public String newpwd(HttpSession session,String oldpwd,String newpwd,String vcode,String ecode){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if (ecode.equals(SecureUtil.md5(vcode))){

            if ((user.getPassword()).equals(SecureUtil.md5(oldpwd))){

                user.setPassword(SecureUtil.md5(newpwd));
                userService.editpwd(user);

                session.invalidate();
                return "success";
            }else {
                return "pwdno";
            }
        }else {
            return "coderror";
        }

    }

    //重置密码检查用户名返回邮箱校验
    @ResponseBody
    @RequestMapping("/checkeml")
    public String checkeml(String loginname){
        User user = userService.findByName(loginname);
        if (user.getEmail()!=null){
            String email=user.getEmail();
            System.out.println("成功");
            return email;
        }
        else {
            System.out.println("失败");
            return "no";
        }
    }
    //重置密码提交验证
    @ResponseBody
    @RequestMapping("/forpwd")
    public String forpwd(String loginname,String newpwd,String vcode,String ecode) {
        User user = userService.findByName(loginname);
        if (ecode.equals(SecureUtil.md5(vcode))){
            user.setPassword(SecureUtil.md5(newpwd));
            userService.editpwd(user);
            return "suc";
        }else{
            return "error";
        }
    }
}
